package sandbox.session;

import com.vaadin.server.VaadinService;

/**
 * Base class for session scope context data in Vaadin applications. Session
 * scope data is made available via {@link #get()}. The context data itself is
 * not defined in this class. Create non abstract sub classes to specify context
 * data content.
 *
 * @author rwegner
 */
public abstract class AbstractSessionContext
{
	public AbstractSessionContext()
	{
		super();
		VaadinService.getCurrentRequest()
		             .getWrappedSession()
		             .setAttribute(AbstractSessionContext.class.getName(), this);
	}

	public static AbstractSessionContext get()
	{
		Object result =
				VaadinService.getCurrentRequest()
				             .getWrappedSession()
				             .getAttribute(AbstractSessionContext.class.getName());
		
		if (result == null)
		{
			throw new IllegalStateException("no session context data");
		}
		
		if (false == (result instanceof AbstractSessionContext))
		{
			throw new IllegalStateException(
					"wrong type of session context data: " + result.getClass().getName());
		}
		
		return (AbstractSessionContext) result;
	}
}